using MediatR;
using S.O.Api.Read.Application.Command.Medical;
using S.O.Domain.Dto.Output;
using S.O.Domain.Medical;
using S.O.ErrorCode;
using S.O.Interstructrue.Base;

namespace S.O.Api.Read.Application.Handler.Medical
{
    /// <summary>
    /// 获取挂号记录详细信息处理器
    /// 用于查看单个挂号记录的完整信息
    /// </summary>
    public class GetRegistrationDetailHandler : IRequestHandler<GetRegistrationDetailCommand, APIResult<GetRegistrationListDto>>
    {
        /// <summary>
        /// 挂号记录仓储
        /// </summary>
        private readonly IBaseRepository<RegistrationModel> _registrationRepository;

        /// <summary>
        /// 构造函数，通过依赖注入初始化所需服务
        /// </summary>
        /// <param name="registrationRepository">挂号记录仓储</param>
        public GetRegistrationDetailHandler(IBaseRepository<RegistrationModel> registrationRepository)
        {
            _registrationRepository = registrationRepository;
        }

        /// <summary>
        /// 处理获取挂号记录详细信息命令
        /// </summary>
        /// <param name="request">查询命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>挂号记录详细信息</returns>
        public async Task<APIResult<GetRegistrationListDto>> Handle(GetRegistrationDetailCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 查找挂号记录
                var registration = _registrationRepository.GetModel(request.Id);
                
                if (registration == null || !registration.IsEnable)
                {
                    return new APIResult<GetRegistrationListDto> { Code = APIEnums.Error, Msg = "挂号记录不存在" };
                }
                
                // 转换为DTO
                var dto = new GetRegistrationListDto
                {
                    Id = registration.Id,
                    RegistrationNo = registration.RegistrationNo,
                    CardNo = registration.CardNo,
                    PatientName = registration.PatientName,
                    RegistrationType = registration.RegistrationType,
                    RegistrationFee = registration.RegistrationFee,
                    OtherFee = registration.OtherFee,
                    Department = registration.Department,
                    Doctor = registration.Doctor,
                    RegistrationDate = registration.RegistrationDate,
                    VisitDate = registration.VisitDate,
                    Status = registration.Status,
                    IsEnable = registration.IsEnable
                };
                
                return new APIResult<GetRegistrationListDto> { Code = APIEnums.Success, Data = dto, Msg = "获取挂号详情成功" };
            }
            catch (Exception ex)
            {
                return new APIResult<GetRegistrationListDto> { Code = APIEnums.Error, Msg = $"获取挂号详情失败：{ex.Message}" };
            }
        }
    }
}